package han.cirno.corrupt.components.refresh

import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.withContext
import java.util.concurrent.atomic.AtomicBoolean

class RefreshQueue<T:StatusReceiver>(
    private val coroutineScope: CoroutineScope,
    private val statusReceiver: T,
){
    private val running = AtomicBoolean(false)

    @Synchronized
    fun enqueue(vararg tasks:suspend ()->BackgroundTask<T>)=coroutineScope.run root@ {statusReceiver.run {
        if (running.get())return@root
        running.set(true)
        launch {
            for (t in tasks){
                val task=t()
                val result=withContext(task.dispatcher) {
                    runBlocking { task.run { runTask() } }
                }
                if (result==BackgroundTask.Result.Abort)break
            }
            running.set(false)
        }
    }}
}